package org.sbear.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xxyWi
 */
public class UrlListService {

    private static CuratorFramework client;


    private static List<String> serverUrls = new ArrayList<String>();

    public static void Init() {
        if (client == null) {
            String zookeeperAddress = "192.168.227.129:2181";
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            client = CuratorFrameworkFactory
                    .builder()
                    .retryPolicy(retryPolicy)
                    .connectString(zookeeperAddress)
                    .sessionTimeoutMs(3000)
                    .connectionTimeoutMs(3000)
                    .build();
            client.start();
        }
    }


    public void loadUrl() throws Exception {
        String servicePath = "/service";
        serverUrls = client.getChildren().forPath(servicePath);
    }

    public void asdasd() {
        PathChildrenCache cache = new PathChildrenCache(client, "/service", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        System.out.println("CHILD_ADDED," + event.getData().getPath());
                        break;
                    case CHILD_UPDATED:
                        System.out.println("CHILD_UPDATED," + event.getData().getPath());
                        break;
                    case CHILD_REMOVED:
                        System.out.println("CHILD_REMOVED," + event.getData().getPath());
                        break;
                    default:
                        break;
                }
            }
        });
    }

}
